﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel; 

namespace luanvanFinal
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        
        clsProject project;
        clsConnect connect;
        SqlDataAdapter da;
        DataSet ds;
        
        public Window1()
        {
            InitializeComponent();                       
            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            datagridAddBasic();
            loadImportReq();
            
        }

        public void datagridAddBasic()
        {
            connect = new clsConnect();
            connect.openConnection();
            da = new SqlDataAdapter("select ID, proName as PojectName, proPM as ProjectPM, proCustomer as ProjectCustomer,proStartDay as ProjectStartDay, proEndDay as ProjectEndDay, proNote as ProjectNote from project", connect.StrConnection);
            ds = new DataSet();
            da.Fill(ds);
            datagrid.ItemsSource = ds.Tables[0].DefaultView;
            connect.closeConnection();
        }

        public void loadImportReq()
        {
            String strSQL = "select proName from project";
            clsConnect ketnoi = new clsConnect();
            ketnoi.openConnection();
            SqlDataAdapter da = new SqlDataAdapter(strSQL, ketnoi.Connection);
            DataTable dt = new DataTable();
            da.Fill(dt);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                cbImProject.Items.Add(dt.Rows[i][0]);
                cbProReq.Items.Add(dt.Rows[i][0]);
            }
            cbImProject.SelectedIndex = 0;
            cbProReq.SelectedIndex = 0;
            ketnoi.closeConnection();           

        }

        public void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            datagridAddBasic();
        }

        String[,] data=new String[20,40] ;
        public void rbIm_Checked(object sender, RoutedEventArgs e)
        {
            String filename;
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Filter = "excel files (*.xls)|*.xls|All files (*.*)|*.*"; // Filter files by extension
            dlg.InitialDirectory = "D:";            
            Nullable<bool> result = dlg.ShowDialog();           
            if (result == true)
            {
                
                filename = dlg.FileName;
                int cell = 9;
                DataTable dt = new DataTable();
                dt.Columns.Add("STT");
                dt.Columns.Add("Req ID");
                dt.Columns.Add("Requirement Title");
                dt.Columns.Add("Description");
                dt.Columns.Add("Type");
                dt.Columns.Add("Category");
                dt.Columns.Add("Status");
                dt.Columns.Add("Change status day");

                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                object misValue = System.Reflection.Missing.Value;

                xlApp = new Excel.ApplicationClass();
                xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
                
                int STT = 1;
                
                while (xlWorkSheet.get_Range("A" + cell.ToString(), misValue).Value2 != null)
                {
                    object oReqid = xlWorkSheet.get_Range("A" + cell.ToString(), misValue).Value2;
                    object oReqTittle = xlWorkSheet.get_Range("B" + cell.ToString(), misValue).Value2;
                    object oDescription = xlWorkSheet.get_Range("C" + cell.ToString(), misValue).Value2;
                    object oReqSource = xlWorkSheet.get_Range("D" + cell.ToString(), misValue).Value2;
                    object oType = xlWorkSheet.get_Range("E" + cell.ToString(), misValue).Value2;
                    object oCategory = xlWorkSheet.get_Range("F" + cell.ToString(), misValue).Value2;
                    object oSize = xlWorkSheet.get_Range("G" + cell.ToString(), misValue).Value2;
                    object oDifficulty = xlWorkSheet.get_Range("H" + cell.ToString(), misValue).Value2;
                    object oKey = xlWorkSheet.get_Range("I" + cell.ToString(), misValue).Value2;
                    object oPriority = xlWorkSheet.get_Range("J" + cell.ToString(), misValue).Value2;
                    object oPic = xlWorkSheet.get_Range("K" + cell.ToString(), misValue).Value2;
                    object oCoding = xlWorkSheet.get_Range("L" + cell.ToString(), misValue).Value2;
                    object oStatus = xlWorkSheet.get_Range("M" + cell.ToString(), misValue).Value2;
                    object oChangeDate = xlWorkSheet.get_Range("N" + cell.ToString(), misValue).Value2;
                    object oDesignDate = xlWorkSheet.get_Range("Q" + cell.ToString(), misValue).Value2;
                    object oDesignReviewDate = xlWorkSheet.get_Range("N" + cell.ToString(), misValue).Value2;
                    object oCodedDate = xlWorkSheet.get_Range("S" + cell.ToString(), misValue).Value2;
                    object oCodeReviewDate = xlWorkSheet.get_Range("T" + cell.ToString(), misValue).Value2;
                    object oTestedDate = xlWorkSheet.get_Range("U" + cell.ToString(), misValue).Value2;
                    object oDeliveredDate = xlWorkSheet.get_Range("V" + cell.ToString(), misValue).Value2;
                    object oAcceptedDate = xlWorkSheet.get_Range("W" + cell.ToString(), misValue).Value2;
                    object oCancelledDate = xlWorkSheet.get_Range("X" + cell.ToString(), misValue).Value2;
                    object oNote = xlWorkSheet.get_Range("Y" + cell.ToString(), misValue).Value2;
                    //add dateabase to datagridview
                    DataRow dr = dt.NewRow();
                    dr[0] = STT.ToString();
                    dr[1] = oReqid.ToString();
                    dr[2] = oReqTittle.ToString();
                    dr[3] = oDescription.ToString();
                    dr[4] = oType.ToString();
                    dr[5] = oCategory.ToString();
                    dr[6] = oStatus.ToString();
                    dr[7] = DateTime.FromOADate(double.Parse(oChangeDate.ToString())).ToString();
                    dt.Rows.Add(dr);
                    dt.AcceptChanges();                    
                   
                    //add database to array to show in textblock
                    if (oReqid == null)
                        data[STT - 1, 0] = null;
                    else
                        data[STT-1,0] = oReqid.ToString();
                    if (oReqTittle == null)
                        data[STT - 1, 1] = null;
                    else
                        data[STT-1,1] = oReqTittle.ToString();
                    if (oDescription == null)
                        data[STT - 1, 2] = null;
                    else
                        data[STT - 1, 2] = oDescription.ToString();                    
                    if (oReqSource == null)
                        data[STT - 1, 3] = null;
                    else
                        data[STT-1,3] = oReqSource.ToString();
                    if (oType == null)
                        data[STT - 1, 4] = null;
                    else
                        data[STT - 1, 4] = oType.ToString();
                    
                    if (oCategory == null)
                        data[STT - 1, 5] = null;
                    else
                        data[STT - 1, 5] = oCategory.ToString();
                    if (oSize == null)
                        data[STT - 1, 6] = null;
                    else
                        data[STT - 1, 6] = oSize.ToString();
                    if (oDifficulty == null)
                        data[STT - 1, 7] = null;
                    else
                        data[STT - 1, 7] = oDifficulty.ToString();
                    if (oKey == null)
                        data[STT - 1, 8] = "";
                    else
                        data[STT - 1, 8] = oKey.ToString();
                    if (oPriority == null)
                        data[STT - 1, 9] = "";
                    else
                        data[STT - 1, 9] = oPriority.ToString();
                    if (oPic == null)
                        data[STT - 1, 10] = null;
                    else
                        data[STT - 1, 10] = oPic.ToString();
                    if (oCoding == null)
                        data[STT - 1, 11] = null;
                    else
                        data[STT - 1, 11] = oCoding.ToString();
                    if (oStatus == null)
                        data[STT - 1, 12] = null;
                    else
                        data[STT - 1, 12] = oStatus.ToString();
                    if (oChangeDate == null)
                        data[STT - 1, 13] = null;
                    else
                        data[STT - 1, 13] = DateTime.FromOADate(double.Parse(oChangeDate.ToString())).ToString();
                    if (oDesignReviewDate == null)
                        data[STT - 1, 14] = null;
                    else
                        data[STT - 1, 14] = DateTime.FromOADate(double.Parse(oDesignReviewDate.ToString())).ToString(); ;
                    if (oCodedDate == null)
                        data[STT - 1, 15] = null;
                    else
                        data[STT - 1, 15] = DateTime.FromOADate(double.Parse(oCodedDate.ToString())).ToString();
                    if (oCodeReviewDate == null)
                        data[STT - 1, 16] = null;
                    else
                        data[STT - 1, 16] = DateTime.FromOADate(double.Parse(oCodeReviewDate.ToString())).ToString();
                    if (oTestedDate == null)
                        data[STT - 1, 17] = null;
                    else
                        data[STT - 1, 17] = DateTime.FromOADate(double.Parse(oTestedDate.ToString())).ToString();
                    if (oDeliveredDate == null)
                        data[STT - 1, 18] = null;
                    else
                        data[STT - 1, 18] = DateTime.FromOADate(double.Parse(oDeliveredDate.ToString())).ToString();
                    if (oAcceptedDate == null)
                        data[STT - 1, 19] = null;
                    else
                        data[STT - 1, 19] = DateTime.FromOADate(double.Parse(oAcceptedDate.ToString())).ToString();
                    if (oCancelledDate == null)
                        data[STT - 1, 20] = null;
                    else
                        data[STT - 1, 20] = DateTime.FromOADate(double.Parse(oCancelledDate.ToString())).ToString();
                    if (oNote == null)
                        data[STT - 1, 21] = null;
                    else
                        data[STT - 1, 21] = oNote.ToString();
                    
                    // STT++ & cell++
                    STT++;
                    cell++;
                }
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();
                dtgReq.ItemsSource = dt.DefaultView;                
            }
        }
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            showDataReq();
        }

        private void dtgReq_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            showDataReq();
        }
        //Import data to Req tab
        public void showDataReq()
        {
            tbReqId.Text = data[dtgReq.SelectedIndex, 0];
            tbReqTitle.Text = data[dtgReq.SelectedIndex, 1];
            Paragraph para = new Paragraph();
            para.Inlines.Add(new Run(data[dtgReq.SelectedIndex, 2].ToString()));
            FlowDocument fd = new FlowDocument(para);
            rtbReqDescription.Document = fd;
            cbReqResource.Text = data[dtgReq.SelectedIndex, 3];
            cbReqType.Text = data[dtgReq.SelectedIndex, 4];
            cbReqCate.Text = data[dtgReq.SelectedIndex, 5];
            cbReqSize.Text = data[dtgReq.SelectedIndex, 6];
            cbReqDif.Text = data[dtgReq.SelectedIndex, 7];
            cbReqKey.Text = data[dtgReq.SelectedIndex, 8];
            cbReqPriority.Text = data[dtgReq.SelectedIndex, 9];
            tbReqPIC.Text = data[dtgReq.SelectedIndex, 10];
            tbReqCodingEffort.Text = data[dtgReq.SelectedIndex, 11];
            cbReqStatus.Text = data[dtgReq.SelectedIndex, 12];
            dpChangeStatus.Text = data[dtgReq.SelectedIndex, 13];
            dpDesignReview.Text = data[dtgReq.SelectedIndex, 14];
            dpCodeDate.Text = data[dtgReq.SelectedIndex, 15];
            dpCodeReview.Text = data[dtgReq.SelectedIndex, 16];
            dpTestDate.Text = data[dtgReq.SelectedIndex, 17];
            dpDeliverDate.Text = data[dtgReq.SelectedIndex, 18];
            dpAcceptDate.Text = data[dtgReq.SelectedIndex, 19];
            dpCancellDate.Text = data[dtgReq.SelectedIndex, 20];
            try
            {
                Paragraph paraNote = new Paragraph();
                paraNote.Inlines.Add(new Run(data[dtgReq.SelectedIndex, 21].ToString()));
                FlowDocument fdNote = new FlowDocument(paraNote);
                rtbReqNote.Document = fdNote;
            }
            catch
            {
                Paragraph paraNote = new Paragraph();
                paraNote.Inlines.Add("");
                FlowDocument fdNote = new FlowDocument(paraNote);
                rtbReqNote.Document = fdNote;
            }
        }

        public void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            connect = new clsConnect();
            connect.openConnection();
            da = new SqlDataAdapter("select ID, proName as PojectName, proPM as ProjectPM, proCustomer as ProjectCustomer,proStartDay as ProjectStartDay, proEndDay as ProjectEndDay, proNote as ProjectNote from project where proName like '%" + tbSearchProject.Text + "%' ", connect.StrConnection);
            ds = new DataSet();
            da.Fill(ds);            
            datagrid.ItemsSource = ds.Tables[0].DefaultView;
            connect.closeConnection();
        }

        public void btnSearchReq_Click(object sender, RoutedEventArgs e)
        {
            String strSQL = "select * from req where idReq like '%" + tbReqSearch.Text + "%' ";
            clsConnect ketnoi = new clsConnect();
            ketnoi.openConnection();
            SqlDataAdapter da = new SqlDataAdapter(strSQL, ketnoi.Connection);
            DataTable dt = new DataTable();
            da.Fill(dt);
            tbReqId.Text = dt.Rows[0][0].ToString();
            tbReqTitle.Text = dt.Rows[0][2].ToString();
            //rtbReqDescription.te = dt.Rows[0][1].ToString();
            Paragraph para = new Paragraph();
            para.Inlines.Add(dt.Rows[0][3].ToString());
            FlowDocument fd = new FlowDocument(para);
            rtbReqDescription.Document = fd;
            
            ketnoi.closeConnection();
            
        }

        private void datagrig_OnDoubleClick(object sender, MouseButtonEventArgs e)
        {
            showdetail();
        }

        public void btnDetail_Click(object sender, RoutedEventArgs e)
        {
            showdetail();
        }

        public void btnStick_Click(object sender, RoutedEventArgs e)
        {
            wdNote note = new wdNote();
            note.Show();
        }

        public void showdetail()
        {
            try
            {
                project = new clsProject();
                connect = new clsConnect();
                DataRowView row = (DataRowView)datagrid.SelectedItems[0];
                String ID = row[0].ToString();
                //MessageBox.Show(ID);
                connect.openConnection();
                wdDetailProject detail = new wdDetailProject();
                string strsql = "select * from project where ID=" + ID;
                DataTable dt = new DataTable();
                dt = project.getDataProject(strsql);
                //MessageBox.Show(dt.Rows[0][0].ToString());
                detail.proName.Text = dt.Rows[0][1].ToString();
                detail.proPM.Text = dt.Rows[0][2].ToString();
                detail.proCus.Text = dt.Rows[0][3].ToString();
                detail.proStartDay.Text = dt.Rows[0][4].ToString();
                detail.proEndDay.Text = dt.Rows[0][5].ToString();
                detail.proProgress1.Text = dt.Rows[0][6].ToString();
                detail.proProgress2.Text = dt.Rows[0][7].ToString();
                detail.proProgress3.Text = dt.Rows[0][8].ToString();
                detail.proProgress4.Text = dt.Rows[0][9].ToString();
                detail.proProgress5.Text = dt.Rows[0][10].ToString();
                detail.proProgress6.Text = dt.Rows[0][11].ToString();
                Paragraph para = new Paragraph();
                para.Inlines.Add(new Run(dt.Rows[0][12].ToString()));
                FlowDocument fd = new FlowDocument(para);
                detail.proNote.Document = fd;
                detail.Show();
                connect.closeConnection();
            }
            catch
            {
                MessageBox.Show("You have to select a row in the list project !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
            }
        }

        public void deleteProject_Click(object sender, RoutedEventArgs e)
        {
            deleteProject();
        }

        public void deleteProject()
        {
            try
            {
                int id;
                project = new clsProject();
                clsProgress progress = new clsProgress();
                clsReq req = new clsReq();
                clsReqChange reqChange = new clsReqChange();
                reqTrace oReqTrace = new reqTrace();
                connect = new clsConnect();
                DataRowView row = (DataRowView)datagrid.SelectedItems[0];
                String ID = row[0].ToString();
                int.TryParse(ID, out id);
                //MessageBox.Show(ID);
                project.ID = id;
                progress.IdProject = id;
                req.IdPro = id;
                reqChange.IdProject = id;
                oReqTrace.IdPro = id;
                project.deleteProject();
                progress.deleteProgress();
                req.deleteReqByIdProject();
                reqChange.deleteReqChangeByIdProject();
                //oReqTrace.deleteReqTrace();
                connect.openConnection();
                clsVersion version = new clsVersion();
                version.IdProject = id;
                version.deleteversionByIdProject();
                clsRisk risk = new clsRisk();
                risk.IdProject = id;
                risk.deleteRiskByIdProject();
                clsStage stage = new clsStage();               
                stage.IdProject = id;                           
                
                String SQLStageDetail = "select Id from stage where idProject='" + id + "'";
                DataTable dt = stage.getDataStage(SQLStageDetail);
                if (dt != null)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        clsStageDetail stageDetail = new clsStageDetail();
                        stageDetail.IdStage = Convert.ToInt32(dt.Rows[i][0].ToString());
                        stageDetail.deleteStageDetailByIdStage();
                    }
                }
                stage.deleteStageByIdProject();
                MessageBox.Show("You have deleted successful!!!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch
            {
                MessageBox.Show("You have to select a row in the list project !!!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void contextDatagrid_Click(object sender, RoutedEventArgs e)
        {
            editProject();
        }

        public void editProject()
        {
            try
            {
                project = new clsProject();
                connect = new clsConnect();
                DataRowView row = (DataRowView)datagrid.SelectedItems[0];
                String ID = row[0].ToString();
                //MessageBox.Show(ID);
                connect.openConnection();
                wdEditPro edit = new wdEditPro(ID);
                string strsql = "select * from project where ID=" + ID;
                DataTable dt = new DataTable();
                dt = project.getDataProject(strsql);
                //MessageBox.Show(dt.Rows[0][0].ToString());
                edit.proName.Text = dt.Rows[0][1].ToString();
                edit.proPM.Text = dt.Rows[0][2].ToString();
                edit.proCus.Text = dt.Rows[0][3].ToString();
                edit.proStartDay.Text = dt.Rows[0][4].ToString();
                edit.proEndDay.Text = dt.Rows[0][5].ToString();
                edit.proProgress1.Text = dt.Rows[0][6].ToString();
                edit.proProgress2.Text = dt.Rows[0][7].ToString();
                edit.proProgress3.Text = dt.Rows[0][8].ToString();
                edit.proProgress4.Text = dt.Rows[0][9].ToString();
                edit.proProgress5.Text = dt.Rows[0][10].ToString();
                edit.proProgress6.Text = dt.Rows[0][11].ToString();
                Paragraph para = new Paragraph();
                para.Inlines.Add(new Run(dt.Rows[0][12].ToString()));
	            FlowDocument fd = new FlowDocument(para);
	            edit.proNote.Document = fd;
                edit.Show();
                connect.closeConnection();
            }
            catch
            {
                MessageBox.Show("You have to select a row in the list project !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
            }
        }

        public void Save_Click(object sender, RoutedEventArgs e)
        {
            
            project = new clsProject();
            Boolean checkprojectname = checkProjectName(TbProjectName.Text);
            project.ProName = TbProjectName.Text;
            project.ProPM = TbPMName.Text;
            project.ProCustomer = TbCosName.Text;
            project.ProStartDay = dpStartDay.SelectedDate;
            project.ProEndDay = dpEndDay.SelectedDate;            
            project.ProNote = new TextRange(tbNote.Document.ContentStart, tbNote.Document.ContentEnd).Text;
            //MessageBox.Show(project.ProStartDay.ToString());
            Nullable<DateTime> tam;
            DateTime?[] progressDate = new DateTime?[6];
            progressDate[0] = dpPro1.SelectedDate;
            progressDate[1] = dpPro2.SelectedDate;
            progressDate[2] = dpPro3.SelectedDate;
            progressDate[3] = dpPro4.SelectedDate;
            progressDate[4] = dpPro5.SelectedDate;
            progressDate[5] = dpPro6.SelectedDate;
            // chuyen gia tri null ve sau
            for (int i = 0; i <= 5; i++)
            {
                if (progressDate[i] == null)
                    for (int j = i + 1; j <= 5; j++)
                    {
                        if (progressDate[j] != null)
                        {
                            progressDate[i] = progressDate[j];
                            progressDate[j] = null;
                            break;
                        }
                    }
            }
            //sap xep theo gia tri tang dan
            for (int i = 0; i < 6; i++)
                for (int j = 0; j < 6; j++)
                    if (progressDate[i] < progressDate[j])
                    {
                        tam = progressDate[i]; progressDate[i] = progressDate[j]; progressDate[j] = tam;
                    }
            //gan gia tri cua cac mang vao cac bien trong class clsProject
            project.ProProgress1 = progressDate[0]; 
            project.ProProgress2 = progressDate[1];
            project.ProProgress3 = progressDate[2];
            project.ProProgress4 = progressDate[3];
            project.ProProgress5 = progressDate[4];
            project.ProProgress6 = progressDate[5];
            // insert vao table progress
            clsProgress progress = new clsProgress();
            progress.Progress1 = progressDate[0];
            progress.Progress2 = progressDate[1];
            progress.Progress3 = progressDate[2];
            progress.Progress4 = progressDate[3];
            progress.Progress5 = progressDate[4];
            progress.Progress6 = progressDate[5];
            //kiem tra tinh dung dan

            
                if (checkprojectname==true)
                    MessageBox.Show("Project name has existed in database", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                else if (project.ProName == "")
                    MessageBox.Show("Project name can not null !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                else if (project.ProEndDay <= project.ProStartDay)
                {
                    MessageBox.Show("End Day must be greater Start Day !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);

                }
                else if (project.ProStartDay == null)
                    MessageBox.Show("Start Day can not null !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                else if (project.ProEndDay == null)
                    MessageBox.Show("End Day can not null !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                else if (project.ProProgress1 <= project.ProStartDay || project.ProProgress1 >= project.ProEndDay)
                {
                    MessageBox.Show("Progress must be greater Start Day and less than End Day !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                }
                else if (project.ProProgress2 <= project.ProStartDay || project.ProProgress2 >= project.ProEndDay)
                {
                    MessageBox.Show("Progress must be greater Start Day and less than End Day !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                }
                else if (project.ProProgress3 <= project.ProStartDay || project.ProProgress3 >= project.ProEndDay)
                {
                    MessageBox.Show("Progress must be greater Start Day and less than End Day !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                }
                else if (project.ProProgress4 <= project.ProStartDay || project.ProProgress4 >= project.ProEndDay)
                {
                    MessageBox.Show("Progress must be greater Start Day and less than End Day !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                }
                else if (project.ProProgress5 <= project.ProStartDay || project.ProProgress5 >= project.ProEndDay)
                {
                    MessageBox.Show("Progress must be greater Start Day and less than End Day !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                }
                else if (project.ProProgress6 <= project.ProStartDay || project.ProProgress6 >= project.ProEndDay)
                {
                    MessageBox.Show("Progress must be greater Start Day and less than End Day !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
                }
                //thuc hien insert
                else
                {
                    project.insertProject();
                    MessageBox.Show("You have insert success !!!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                String strSQL = "select MAX(ID) from project";
                clsConnect ketnoi = new clsConnect();
                ketnoi.openConnection();
                SqlDataAdapter da = new SqlDataAdapter(strSQL, ketnoi.Connection);
                DataTable dt = new DataTable();
                da.Fill(dt);                
                ketnoi.closeConnection();
                try
                {
                    progress.IdProject = Convert.ToInt32(dt.Rows[0][0].ToString());
                    progress.insertProgress();
                }
                catch
                {
                }
        }

        public Boolean checkProjectName( String name)
        {
            Boolean result = false;
            project = new clsProject();
            DataTable dt = project.getProjectName();
            //String [] proName = new String();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (name == dt.Rows[i][0].ToString())               
                    result = true;                 
                
            }
            return result;
        }

        private void datagrid_LoadingRow(object sender, Microsoft.Windows.Controls.DataGridRowEventArgs e)
        {

        }

        public void btnApply_Click(object sender, RoutedEventArgs e)
        {
            clsReq req = new clsReq();
            clsProject project = new clsProject();
            String idProNames = project.getIdFromName(cbImProject.Text); //lay id tu project name
            int idProName;
            int.TryParse(idProNames, out idProName);
            req.IdReq = tbReqId.Text;
            req.IdPro = idProName;
            req.ReqTitle = tbReqTitle.Text;
            req.ReqDescription = new TextRange(rtbReqDescription.Document.ContentStart, rtbReqDescription.Document.ContentEnd).Text;
            req.ReqResource = cbReqResource.Text;
            req.Type = cbReqType.Text;
            req.Category = cbReqCate.Text;
            req.Size = cbReqSize.Text;
            req.Difficulty = cbReqDif.Text;
            req.ReqKey = cbReqKey.Text;
            req.Priority = cbReqPriority.Text;
            req.Pic = tbReqPIC.Text;
            req.Coding = tbReqCodingEffort.Text;
            req.Status = cbReqStatus.Text;
            req.Change = dpChangeStatus.SelectedDate;
            req.Note = new TextRange(rtbReqNote.Document.ContentStart, rtbReqNote.Document.ContentEnd).Text;
            req.DesignReviewed = dpDesignReview.SelectedDate;
            req.CodedDate = dpCodeDate.SelectedDate;
            req.TestedDate = dpTestDate.SelectedDate;
            req.DeliveredDate = dpDeliverDate.SelectedDate;
            req.AcceptedDate = dpAcceptDate.SelectedDate;
            req.CancelledDate = dpCancellDate.SelectedDate;
            //lay cac IdReq co san trong data 
            bool kt = true;
            String strSQL = "select idReq,idPro from req";
            clsConnect ketnoi = new clsConnect();
            ketnoi.openConnection();
            SqlDataAdapter da = new SqlDataAdapter(strSQL, ketnoi.Connection);
            DataTable dt = new DataTable();
            da.Fill(dt);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (req.IdReq == dt.Rows[i][0].ToString() && req.IdPro == Convert.ToInt32(dt.Rows[i][1]))
                    kt=false;
            }
            ketnoi.closeConnection();
            if (req.IdReq == "")
                MessageBox.Show("Req Id can not null", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
            else if (req.ReqTitle == "")
                MessageBox.Show("Req tittle name can not null !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
            else if (kt==false)
                MessageBox.Show("Id Requirement and Project can not valid", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
            else
            {
                req.insertReq();                
                clsVersion version = new clsVersion();
                version.IdProject = idProName;
                version.IdReq = tbReqId.Text;
                version.VClass = cbReqClass.Text;
                version.insertVersion();
                MessageBox.Show("You have insert success !!!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
            }   
        }

        public void showSearchResultRequirement()
        {
            connect = new clsConnect();
            connect.openConnection();
            da = new SqlDataAdapter("select idReq, proName as PojectName, proPM as ProjectPM, proCustomer as ProjectCustomer,proStartDay as ProjectStartDay, proEndDay as ProjectEndDay, proNote as ProjectNote from project", connect.StrConnection);
            ds = new DataSet();
            da.Fill(ds);
            dtgRequiment.ItemsSource = ds.Tables[0].DefaultView;
            connect.closeConnection();
        }

        String idProSearch;
        private void btnSearchReq_Click_1(object sender, RoutedEventArgs e)
        {
            clsProject project = new clsProject();
            String idProject = project.getIdFromName(cbProReq.Text);
            idProSearch = idProject;
            connect = new clsConnect();
            connect.openConnection();
            da = new SqlDataAdapter("select idReq, reqTitle as Tittle, reqDescription as Description, reqResource as Resource,ReqType as Type, note as Note, change as ChangeStatusDate  from req where idPro = '"+idProject+"'", connect.StrConnection);
            ds = new DataSet();
            da.Fill(ds);
            dtgRequiment.ItemsSource = ds.Tables[0].DefaultView;
            connect.closeConnection();
        }

        private void dtgRequiment_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                
                connect = new clsConnect();
                DataRowView row = (DataRowView)dtgRequiment.SelectedItems[0];                
                String IDReq = row[0].ToString();
                clsReq req = new clsReq();
                req = req.getReqFromID(IDReq,idProSearch);
                tbReqIdR.Text = req.IdReq;
                tbReqTitleR.Text = req.ReqTitle.ToString();
                Paragraph para = new Paragraph();
                para.Inlines.Add(new Run(req.ReqDescription.ToString()));
                FlowDocument fd = new FlowDocument(para);
                rtbReqDescriptionR.Document = fd;
                cbReqResourceR.Text = req.ReqResource.ToString();
                cbReqTypeR.Text = req.Type.ToString();
                cbReqCateR.Text = req.Category.ToString();
                cbReqSizeR.Text = req.Size.ToString();
                cbReqDifR.Text = req.Difficulty.ToString();
                cbReqKeyR.Text = req.ReqKey.ToString();
                cbReqPriorityR.Text = req.Priority.ToString();
                tbReqPICR.Text = req.Pic.ToString();
                tbReqCodingEffortR.Text = req.Coding.ToString();
                cbReqStatusR.Text = req.Status.ToString();                
                dpChangeStatusR.Text = req.Change.ToString();
                dpDesignReviewR.Text = req.DesignReviewed.ToString();
                dpCodeDateR.Text = req.CodedDate.ToString();
                dpTestDateR.Text = req.TestedDate.ToString();
                dpDeliverDateR.Text = req.DeliveredDate.ToString();
                dpAcceptDate.Text = req.AcceptedDate.ToString();
                dpCancellDateR.Text = req.CancelledDate.ToString();
                Paragraph para1 = new Paragraph();
                para1.Inlines.Add(new Run(req.Note.ToString()));
                FlowDocument fd1 = new FlowDocument(para1);
                rtbReqNoteR.Document = fd1;
                //string strsql = "select * from project where ID=" + ID;
                //MessageBox.Show(IDReq);
            }
            catch
            {
            }
        }

        private void btnReqEdit_Click(object sender, RoutedEventArgs e)
        {
            clsReq req = new clsReq();
            clsProject project = new clsProject();
            String idProNames = project.getIdFromName(cbProReq.Text); //lay id tu project name
            int idProName;
            int.TryParse(idProNames, out idProName);
            req.IdReq = tbReqIdR.Text;
            req.IdPro = idProName;
            req.ReqTitle = tbReqTitleR.Text;
            req.ReqDescription = new TextRange(rtbReqDescriptionR.Document.ContentStart, rtbReqDescriptionR.Document.ContentEnd).Text;
            req.ReqResource = cbReqResourceR.Text;
            req.Type = cbReqTypeR.Text;
            req.Category = cbReqCateR.Text;
            req.Size = cbReqSizeR.Text;
            req.Difficulty = cbReqDifR.Text;
            req.ReqKey = cbReqKeyR.Text;
            req.Priority = cbReqPriorityR.Text;
            req.Pic = tbReqPICR.Text;
            req.Coding = tbReqCodingEffortR.Text;
            req.Status = cbReqStatusR.Text;
            req.Change = dpChangeStatusR.SelectedDate;
            req.Note = new TextRange(rtbReqNoteR.Document.ContentStart, rtbReqNoteR.Document.ContentEnd).Text;
            req.DesignReviewed = dpDesignReviewR.SelectedDate;
            req.CodedDate = dpCodeDateR.SelectedDate;
            req.TestedDate = dpTestDateR.SelectedDate;
            req.DeliveredDate = dpDeliverDateR.SelectedDate;
            req.AcceptedDate = dpAcceptDateR.SelectedDate;
            req.CancelledDate = dpCancellDateR.SelectedDate;
            //lay cac IdReq co san trong data 
            
            if (req.IdReq == "")
                MessageBox.Show("Req Id can not null", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);
            else if (req.ReqTitle == "")
                MessageBox.Show("Req tittle name can not null !!!", "Warrning", MessageBoxButton.OK, MessageBoxImage.Stop);            
            else
            {
                req.updateReq();
                MessageBox.Show("You have insert success !!!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
            } 
        }

        public void deleteReq()
        {
            try
            {
                
                clsReq req = new clsReq();
                connect = new clsConnect();
                project = new clsProject();
                String idProNames = project.getIdFromName(cbProReq.Text); //lay id tu project name
                int idProName;
                int.TryParse(idProNames, out idProName);
                //MessageBox.Show(ID);
                req.IdReq = tbReqIdR.Text.ToString();
                req.IdPro = idProName;
                req.deleteReq();
                connect.openConnection();
                //xoa reqTrace
                reqTrace reqTrace = new reqTrace();
                reqTrace.IdReq = tbReqIdR.Text.ToString();
                reqTrace.deleteReqTraceByIdReq();
                //xoa version
                clsVersion version = new clsVersion();
                version.IdProject = idProName;
                version.IdReq = tbReqIdR.Text.ToString();
                version.deleteversionByIdReq();
           }
            catch
            {
                MessageBox.Show("Error while deleting", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnReqDelete_Click(object sender, RoutedEventArgs e)
        {
            deleteReq();
        }

        private void btnReqChange_Click(object sender, RoutedEventArgs e)
        {
            WdReqChange reqChange = new WdReqChange();
            reqChange.Show();
            
        }

        private void btnRisk_Click(object sender, RoutedEventArgs e)
        {
            wdRiskFirst1 riskFirst1 = new wdRiskFirst1();
            riskFirst1.Show();
        }

        

        private void Sys_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("sadsa");
        }

        private void btnMatrix_Click(object sender, RoutedEventArgs e)
        {
            wdReqRiskFirst reqRiskFirst = new wdReqRiskFirst();
            reqRiskFirst.Show();
        }

        private void btnProgress_Click(object sender, RoutedEventArgs e)
        {
            wdProgressForm progressForm = new wdProgressForm();
            progressForm.Show();
            //wdProgress progress = new wdProgress();
            //progress.Show();
        }

        private void btnReqTrace_Click(object sender, RoutedEventArgs e)
        {
            wdReqTrace reqTrace = new wdReqTrace();
            reqTrace.Show();
        }

        private void btnVersion_Click(object sender, RoutedEventArgs e)
        {
            wdVersion version = new wdVersion();
            version.Show();
        }

        private void btnCreateProject_Click(object sender, RoutedEventArgs e)
        {
            wdProjectCreate projectCreate = new wdProjectCreate();
            projectCreate.Show();
        }
        
    }
}
